#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
逐行分析文件，精确定位_process_loop方法并检查其结构
"""

# 读取文件内容
with open('d:/未知/yolo_apply/video_processing/video_processor.py', 'r', encoding='utf-8') as f:
    all_lines = f.readlines()

# 找到_process_loop方法的开始和结束位置
method_start = None
method_end = None
indent_level = None

print("搜索_process_loop方法...")
for i, line in enumerate(all_lines):
    stripped = line.strip()
    
    # 找到方法定义
    if stripped.startswith('def _process_loop(self):'):
        method_start = i
        # 计算方法体的缩进级别
        indent_level = len(line) - len(line.lstrip()) + 4  # 方法体应该比def多一级缩进
        print(f"找到方法开始于第{i+1}行")
        break

# 如果找到了方法开始，查找方法结束
if method_start is not None:
    # 分析方法结构
    try_stack = []
    in_method = True
    
    print(f"\n分析_process_loop方法的try-except-finally结构:")
    print("-" * 70)
    print(f"{'行号':<6} {'缩进级别':<10} {'代码类型':<15} {'内容'}")
    print("-" * 70)
    
    for i in range(method_start, len(all_lines)):
        line = all_lines[i]
        stripped = line.strip()
        current_indent = len(line) - len(line.lstrip())
        
        # 检查是否是方法结束
        if i > method_start and current_indent < indent_level and stripped.startswith('def '):
            method_end = i - 1
            print(f"找到方法结束于第{i}行前")
            break
        
        # 检查try-except-finally块
        code_type = ""
        if stripped.startswith('try:'):
            code_type = "try"
            try_stack.append({'type': 'try', 'indent': current_indent, 'line': i+1})
        elif stripped.startswith('except'):
            code_type = "except"
            # 找到匹配的try块
            matched = False
            j = len(try_stack) - 1
            while j >= 0:
                if try_stack[j]['type'] == 'try' and try_stack[j]['indent'] == current_indent:
                    try_stack.append({'type': 'except', 'indent': current_indent, 'line': i+1})
                    matched = True
                    break
                j -= 1
            if not matched:
                print(f"警告: 第{i+1}行的except块没有匹配的try块!")
        elif stripped.startswith('finally:'):
            code_type = "finally"
            # 找到匹配的try块
            matched = False
            j = len(try_stack) - 1
            while j >= 0:
                if try_stack[j]['type'] == 'try' and try_stack[j]['indent'] == current_indent:
                    try_stack.append({'type': 'finally', 'indent': current_indent, 'line': i+1})
                    matched = True
                    break
                j -= 1
            if not matched:
                print(f"警告: 第{i+1}行的finally块没有匹配的try块!")
        
        # 打印关键行
        if code_type:
            print(f"{i+1:<6} {current_indent:<10} {code_type:<15} {stripped[:50]}{'...' if len(stripped) > 50 else ''}")
    
    # 检查未匹配的try块
    print("\n检查未匹配的try块:")
    unmatched_tries = []
    for block in try_stack:
        if block['type'] == 'try':
            # 检查这个try块是否有对应的except或finally
            has_match = False
            for b in try_stack[try_stack.index(block)+1:]:
                if (b['type'] in ['except', 'finally'] and 
                    b['indent'] == block['indent']):
                    has_match = True
                    break
            if not has_match:
                unmatched_tries.append(block)
    
    if unmatched_tries:
        print(f"发现{len(unmatched_tries)}个未匹配的try块:")
        for block in unmatched_tries:
            print(f"  - 第{block['line']}行，缩进级别: {block['indent']}")
            # 打印该try块附近的代码
            start = max(0, block['line'] - 2 - 1)  # 转换为0-based索引
            end = min(len(all_lines), block['line'] + 5 - 1)
            for j in range(start, end):
                print(f"    第{j+1}行: {all_lines[j].rstrip()}")
    else:
        print("所有try块都有匹配的except或finally块。")
    
    # 输出错误行附近的上下文
    error_line = 1848  # 错误在第1849行，我们看第1848行
    print(f"\n错误行(1849)附近的上下文:")
    print("-" * 70)
    start = max(0, error_line - 10 - 1)  # 转换为0-based索引
    end = min(len(all_lines), error_line + 10 - 1)
    for j in range(start, end):
        indent = len(all_lines[j]) - len(all_lines[j].lstrip())
        print(f"第{j+1}行 [{indent}]: {all_lines[j].rstrip()}")
    print("-" * 70)
    
else:
    print("未找到_process_loop方法")